/**
 * 由虚拟dom创建真实dom
 *
 * @param {vnode} vnode
 * @return {Element} 
 */
function createElem(vnode) {
  const { sel, data = {}, children = [], text = undefined } = vnode;

  const elm = document.createElement(sel);
  // 保存真实dom指向到虚拟dom
  vnode.elm = elm;

  for (const attr in data) {
    // 处理类名
    if (attr === 'class') {
      for (const cls in data[attr]) {
        if (data[attr][cls]) {
          elm.classList.add(cls);
        }
      }
      continue;
    }
    // 处理样式
    if (attr === 'style') {
      for (const s in data[attr]) {
        elm.style[s] = data[attr][s];
      }
      continue;
    }
    // 添加属性
    elm.setAttribute(attr, data[attr]);
  }

  if (text) elm.innerText = text;

  // 递归生成子元素并添加到父元素
  for (let i = 0, len = children.length; i < len; i++) {
    elm.appendChild(createElem(children[i]));
  }

  return elm;
}

export default createElem;
